#!/bin/bash

# 颜色定义
RED=$'\e[31m'
GREEN=$'\e[32m'
YELLOW=$'\e[33m'
BLUE=$'\e[34m'
MAGENTA=$'\e[35m'
CYAN=$'\e[36m'
NC=$'\e[0m'
BOLD=$'\e[1m'

# 图标定义
ICON_SUCCESS="✅"
ICON_ERROR="❌"
ICON_INFO="ℹ️"
ICON_DEBUG="🔍"
ICON_DEPLOY="🚀"

# 全局变量
DEPLOY_SWARM_HOME="${HOME}/.deploy-swarm"
LIB_DIR="$(dirname "${BASH_SOURCE[0]}")"
BUILD_LOG="$DEPLOY_SWARM_HOME/build.log"
TEMP_DIR=""
DEPLOY_SUCCESS=false

# 镜像标签全局变量
IMAGE_TAG=""

# Spinner变量
SPINNER_PID=""
SPINNER_MESSAGE=""

# 初始化临时目录
init_temp_dir() {
    debug "开始初始化临时目录"
    debug "DEPLOY_SWARM_HOME: $DEPLOY_SWARM_HOME"
    
    TEMP_DIR="$DEPLOY_SWARM_HOME/temp"
    debug "TEMP_DIR: $TEMP_DIR"
    
    # 清理旧的临时目录
    rm -rf "$TEMP_DIR"
    mkdir -p "$TEMP_DIR"
    
    if $DEBUG_MODE; then
        debug "临时目录结构:"
        ls -la "$TEMP_DIR"
    fi
}

# 清理临时文件
cleanup() {
    local keep_log="${1:-false}"
    debug "开始清理临时文件"
    
    if [ "$keep_log" = "true" ]; then
        debug "保留日志文件，清理其他临时文件"
        find "$TEMP_DIR" -type f ! -name "*.log" -delete 2>/dev/null
    else
        rm -rf "$TEMP_DIR"
    fi
}

# 错误处理
handle_error() {
    local message="$1"
    echo "${RED}${ICON_ERROR} 错误: $message${NC}" >&2
    cleanup
    exit 1
}

# 调试日志
debug() {
    if $DEBUG_MODE; then
        local caller_info
        caller_info="$(basename "${BASH_SOURCE[1]}"):${BASH_LINENO[0]}"
        echo "${BLUE}${ICON_DEBUG} [DEBUG] ($caller_info) $1${NC}" >&2
    fi
}

# 成功消息
success() {
    echo "${GREEN}${ICON_SUCCESS} $1${NC}" >&2
}

# 信息消息
info() {
    echo "${CYAN}${ICON_INFO} $1${NC}" >&2
}

# 警告消息
warning() {
    echo "${YELLOW}⚠️ $1${NC}" >&2
}

# 设置调试模式
set_debug_mode() {
    export DEBUG_MODE=$1
    debug "调试模式已设置为: $1"
}

# 设置镜像标签
set_image_tag() {
    local project_name="$1"
    local tag="$2"
    IMAGE_TAG="${tag:-${DEPLOY_ENV:-local}}"
    debug "设置镜像标签: $project_name:$IMAGE_TAG"
}

# 获取镜像标签
get_image_tag() {
    echo "$IMAGE_TAG"
}

# 启动spinner
start_spinner() {
    SPINNER_MESSAGE="$1"
    
    # 如果已经有spinner在运行，先停止它
    stop_spinner >/dev/null 2>&1
    
    # 启动spinner后台进程
    {
        frames=('⣾' '⣽' '⣻' '⢿' '⡿' '⣟' '⣯' '⣷')
        colors=("$BLUE" "$CYAN" "$GREEN" "$YELLOW" "$MAGENTA")
        color_index=0
        
        while true; do
            for frame in "${frames[@]}"; do
                color="${colors[$color_index]}"
                printf $'\r%s[%s] %s%s' "$color" "$frame" "$SPINNER_MESSAGE" "$NC"
                color_index=$(( (color_index + 1) % ${#colors[@]} ))
                sleep 0.1
            done
        done
    } 2>/dev/null &
    
    SPINNER_PID=$!
    disown "$SPINNER_PID" 2>/dev/null
}

# 停止spinner
stop_spinner() {
    local type="$1"
    local message="$2"
    
    # 如果spinner正在运行，停止它
    if [ -n "$SPINNER_PID" ]; then
        kill -9 "$SPINNER_PID" >/dev/null 2>&1
        wait "$SPINNER_PID" >/dev/null 2>&1 || true
        SPINNER_PID=""
        
        # 清除spinner行
        printf $'\r%-80s\r' ""
        
        # 显示结果消息
        case "$type" in
            "success")
                echo "${GREEN}${ICON_SUCCESS} $message${NC}" >&2
                ;;
            "error")
                echo "${RED}${ICON_ERROR} $message${NC}" >&2
                ;;
            *)
                echo "${BLUE}${ICON_INFO} $message${NC}" >&2
                ;;
        esac
    fi
}
